package cc.telecomdigital.tdstock.trading.Services;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class TradeGetClientCert
{
	private String	LOG_TAG	= "TradeGetClientCert";

	// Call back interface
	public interface ITradeGetClientCertResponse
	{
		/** if iSuccessfulSend == false, it means the there is a communication error
			do not consider the iReponse as valid response **/
		void ResponseFunc(boolean iSuccessfulSend);
	}

	private Context	callerContext;
	private Handler	messageHandler;
	private String      urlString;

	/** Create a Get Cert request with a caller **/
	public TradeGetClientCert(Context iContext)
	{
		callerContext = iContext;
		urlString = ConstructGetCertURL(iContext);
	}

	public String ConstructGetCertURL(Context iOwnerContext)
	{
		String formatString;
		
		formatString = String.format( TradeAppInfo.certURL, TradeAppInfo.GetDeviceID(iOwnerContext),
								DeviceInfo.GetCurrentDateStamp()); 
		
		return formatString;			
	}
	
	private ITradeGetClientCertResponse	responseHandler;

	/** If we are running a demo version, the iUseDemoData could be a fake send **/
	public void SendRequest( ITradeGetClientCertResponse iTradeGetClientCertResponse)
	{
		responseHandler = iTradeGetClientCertResponse;
		messageHandler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				if (responseHandler == null)
					return;

				switch (msg.what)
				{
					case REQUEST_DATA_SENT_FAIL:
						responseHandler.ResponseFunc(false);
						break;

					case REQUEST_DATA_SENT_SUCCESS:
						responseHandler.ResponseFunc(true);
						break;
				}
			}
		};
		// Start the Thread
		Thread internalThreadObj = new Thread()
		{
			@Override
			public void run()
			{
				Message msg;
				boolean dataStatus;

				// Provide success or fail reply
				msg = new Message();
				dataStatus = SendData();
				// Determine this is a successful data or not
				if (!dataStatus)
					msg.what = REQUEST_DATA_SENT_FAIL;
				else
					msg.what = REQUEST_DATA_SENT_SUCCESS;
				messageHandler.sendMessage(msg);
			}			
		};
		internalThreadObj.start();
	}

	private final int	REQUEST_DATA_SENT_FAIL		= 0;
	private final int	REQUEST_DATA_SENT_SUCCESS	= 1;

	private boolean SendData()
	{
		//Prevent for multiple call for network
		synchronized(TradeAppInfo.padLock)
		{		
			boolean statusCode;
			InputStream inStream;
			FileOutputStream fileStream;
			// BufferedInputStream bufferStream;
	
			statusCode = false;
			TradeAppInfo.FlushClientCertIfExist(callerContext);
			if (!DeviceInfo.IsNetworkAvailable(callerContext))
				return statusCode;
	
			fileStream = null;
			inStream = null;
			// bufferStream = null;
			try
			{
				URL url;
				URLConnection urlConnection;
				File newFile;
				
				url = new URL(urlString);
				// Open a connection to that URL.
				urlConnection = url.openConnection();
				urlConnection.setConnectTimeout(TradeAppInfo.SOAP_COMMUNIC_Timeout);
				urlConnection.setReadTimeout(10000);
	
				try
				{
					newFile = TradeAppInfo.CreateClientCertFile(callerContext);
				}
				catch (Exception ex)
				{
					ex.printStackTrace();
					TDStockLog.e(LOG_TAG, "Ex: " + ex.toString());
					return false;
				}
	
				// Basic way to save our copy of certificate from stream
				inStream = urlConnection.getInputStream();
				fileStream = new FileOutputStream(newFile);
				int readByte;
				
				while ((readByte = inStream.read()) != -1)
				{
					fileStream.write(readByte);
				}
			
				fileStream.close();
				fileStream = null;
	
				// Close inStream
				inStream.close();
				inStream = null;
				statusCode = true;
	
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
				TDStockLog.e(LOG_TAG, "Ex: " + ex.toString());
				// Flush the file, container
				TradeAppInfo.FlushClientCertIfExist(callerContext);
			}
	
			finally
			{
				if (fileStream != null)
				{
					try
					{
						fileStream.close();
					}
					catch (IOException e1)
					{
						e1.printStackTrace();
						TDStockLog.e(LOG_TAG, "inStream close: " + e1.toString());
					}
				}
	
				if (inStream != null)
				{
					try
					{
						inStream.close();
					}
					catch (IOException e2)
					{
						e2.printStackTrace();
						TDStockLog.e(LOG_TAG, "inStream close: " + e2.toString());
					}
				}
			}
			return statusCode;
		}
	}
}
